package cn.itsource.org.service.Impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.service.Impl.BaseSerivcelmpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.EmailService;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.EmployeeService;
import cn.itsource.org.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional//事务管理
public class ShopServiceImpl extends BaseSerivcelmpl<Shop, ShopQuery> implements ShopService {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisService redisService;

    @Override
    public AjaxResult settlement(Shop shop) {
        //先写主体，再写细节
        //验证规则自己去加  验证密码
        //1.新增员工到数据库
        Employee admin = shop.getAdmin();//没有id
        if (!StrUtil.equals(admin.getPassword(),admin.getComfirmPassword())){
            throw new RuntimeException("两次密码不一致");
        }
        //1.1判断用户名，手机号，邮箱全部都不能重复
        Employee employee = employeeService.checkRepeatEmployee(admin);
        if (employee != null){
            throw new RuntimeException("请检查用户名，手机号，邮箱有可能有一个重复了");
        }

        //uuid生成盐值
        /*String salt = IdUtil.fastSimpleUUID();
        String pwd = MD5.create().setSalt(salt.getBytes()).digestHex(admin.getPassword());
        //盐值和加密之后的密码入库
        admin.setSalt(salt);
        admin.setPassword(pwd);*/

        //调用钩子函数
        admin.md5Pwd();

        employeeService.save(admin);

        //拿到员工自增id,设置到店铺管理
        shop.setAdmin(admin);

        //新增店铺信息
        shopMapper.insertShop(shop);
        //拿到店铺id,设置员工,修改员工
        admin.setShopId(shop.getId());
        employeeService.update(admin);

        String uuid = IdUtil.fastSimpleUUID();
        //5.发送邮件
        emailService.sendEMail("宠物乐园激活",
                "Congratulations,审核通过,请点击链接激活,http://localhost/shop/jihuo/"+uuid+"/"+shop.getId(),admin.getEmail());
        //5.1redis存数据 key:uuid  value：店铺id
        redisService.setStringKeyAndValue(uuid,shop.getId(),1);

        return AjaxResult.createSuccess();
    }
}
